﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace SPALM.MSBuildTasks
{
  public class RestartIIS : DeploymentOperation
  {
    public RestartIIS(Deployment parentTask, int ParsedRetries, int ParsedWaitSecondsAfterFinish, bool ParsedSimulateDeployment)
        : base(parentTask, ParsedRetries, ParsedWaitSecondsAfterFinish, ParsedSimulateDeployment)
    {
    }

    public override void RunOperation()
    {
      try
      {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "iisreset";
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        bool fStarted = p.Start();

        if (!fStarted)
        {
          LogMessage("Unable to start iisreset", LogLevel.High);
        }

        while (!p.HasExited)
        {
          string text = p.StandardOutput.ReadLine();
          Output(text);
          System.Threading.Thread.Sleep(100);
        }

        Output(p.StandardOutput.ReadToEnd());
      }
      catch (Exception ex)
      {
        LogException(ex.Message);
      }

      EnsureRunning("World Wide Web Publishing Service");
    }

    private void Output(string message)
    {
      if (!String.IsNullOrEmpty(message))
      {
        StringReader reader = new StringReader(message);
        string input = "";
        while ((input = reader.ReadLine()) != null)
        {
          if (!string.IsNullOrEmpty(input.Trim()))
          {
            LogMessage(input, LogLevel.Normal);
          }
        }
      }
    }
  }
}
